<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Coupon as CouponModel;
use app\common\model\UserCoupon;
use app\common\model\User;
use think\Config;

/**
 * 优惠券
 */
class Coupon extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['index'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 领券中心
     */
    public function index()
    {
        $state = input('state',1);
        $where['status']='normal';
        if($state==1){
            $where['shop_id']=0;
        }else{
            $where['shop_id']=['>',0];
        }
        $data = (new CouponModel())
            ->where($where)
            ->whereRaw("UNIX_TIMESTAMP(end_date)>".(time()-86399))
            ->field("id,name,limit,price,type,shop_id,start_date,end_date")
            ->order('createtime desc')
            ->paginate()
            ->each(function ($datum) {
                $log = UserCoupon::where(['user_id'=>$this->auth->id,'coupon_id'=>$datum['id']])->find();
                $datum['received'] =$log?1:0;
                return $datum;
            });

        $this->success('ok',$data);
    }

    /**
     * 我的优惠券
     */
    public function mine()
    {
        $where['user_id']=$this->auth->id;
        $status = input('status');
        if($status) $where['status']=$status;
        $list = (new UserCoupon())
            ->where($where)
            ->field("id,limit,coupon_id,price,way,shop_id,status,starttime,expiredtime")
            ->order('createtime desc')
            ->paginate()
            ->each(function($data, $index){
                $data['type'] = $data['limit']>0?1:2;
                $data['start_date'] = datetime($data['starttime'],'Y-m-d');
                $data['end_date'] = datetime($data['expiredtime'],'Y-m-d');
                return $data;
            });
        $this->success('ok',$list);
    }

    /**
     * 领取优惠券
     */
    public function receive(){
        $id = input('id');
        $coupon = CouponModel::get($id);
        if(!$id || !$coupon) $this->error(__('参数错误'));
        $userCoupon = UserCoupon::where(['user_id'=>$this->auth->id,'coupon_id'=>$id])->find();
        if($userCoupon) $this->error(__('你已经领取过该优惠券'));
        $result = User::receive_coupon($this->auth->id,$coupon['price'],strtotime($coupon['start_date']),strtotime($coupon['end_date'])+86399,$coupon['limit'],'receive',$coupon['shop_id'],$coupon['id']);
        $result?$this->success(__('领取成功'),['coupon_id'=>$id]):$this->error(__('领取失败'));
    }

}
